<template>
  <a-modal v-model:open="visible" ok-tixt="保存" destroy-on-close centered title="编辑角色" :confirm-loading="loading" width="800px" @ok="submit">
    <div class="edit-role-box">
      <a-form ref="formRef" :model="formData" name="basic" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" autocomplete="off">
        <a-form-item label-align="left" label="角色名称" name="roleName" :rules="[{ required: true, message: '请输入角色名称' }]">
          <a-input v-model:value="formData.roleName" />
        </a-form-item>
        <a-form-item label-align="left" label="备注" name="remark">
          <a-input v-model:value="formData.remark" />
        </a-form-item>
        <a-form-item label-align="left" label="排序" name="sort">
          <a-input v-model:value="formData.sort" />
        </a-form-item>
        <a-form-item label-align="left" label="角色状态" name="status">
          <a-radio-group v-model:value="formData.status" :options="statusOptions" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup>
const emit = defineEmits(['update:open', 'change'])

const visible = ref(false)

const emptyForm = {
  id: null, // 角色ID
  roleName: '', // 角色名称
  remark: '', // 备注
  sort: 0, // 排序
  status: 0, // 状态 0 启用 1 禁用
}

const formRef = ref()
const loading = ref(false)

const statusOptions = [
  { label: '启用', value: 0 },
  { label: '禁用', value: 1 },
]

const formData = reactive({ ...emptyForm })

async function submit() {
  await formRef.value.validate()
  loading.value = true
  // 提交表单数据
  const requestUrl = formData.id ? '/admin/role/update' : '/admin/role/add'
  await httpRequest(requestUrl, formData)
  message.success('操作成功')
  visible.value = false
  loading.value = false
  emit('change', formData) // 通知父组件更新数据
}

function edit(role) {
  if (role) {
    // 如果传入了角色数据，则编辑
    Object.assign(formData, role)
  }
  else {
    // 否则重置表单
    Object.assign(formData, emptyForm)
  }
  Object.assign(formData, role)
  visible.value = true
}

defineExpose({ edit })
</script>

<style lang="less" scoped>
.edit-role-box {
  width: 600px;
  padding-top: 30px;
}

.menu-tree {
  width: 100%;
  height: 40vh;
  padding: 10px;
  overflow-y: auto;
  border: 1px solid #f5f7f5;
}
</style>
